﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using urBook.Engine;

namespace urBook.Gui
{
    /// <summary>
    /// Interaction logic for ConfigurationDialog.xaml
    /// </summary>
    public partial class ConfigurationDialog : UserControl
    {
        MainWindow root;
        PopupWindow popup;
        ContactCard contact;
        bool defaultConfiguration;
        Color red = new Color()
        {
            ScA = 1,
            ScR = 1,
            ScG = 0,
            ScB = 0
        };

        public ConfigurationDialog(MainWindow root, bool defaultConfiguration)
        {
            InitializeComponent();
            this.root = root;
            this.popup = new PopupWindow(root);
            this.defaultConfiguration = defaultConfiguration;
            root.Container.Children.Add(popup);
            popup.Container.Children.Add(this);

            Hashtable countries = Utilities.loadCountries(Properties.Resources.CountryCallingCodes);
            List<String> countriesList = new List<string>();
            foreach (string country in countries.Keys)
                countriesList.Add(country);
            countriesList.Sort();
            foreach (string country in countriesList)
            {
                homeCountry.Items.Add(country);
                workCountry.Items.Add(country);
            }

            contact = new ContactCard();
        }

        private void setImageSource(Image image, string source)
        {
            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri(source, UriKind.RelativeOrAbsolute);
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.EndInit();
            image.Source = src;
            image.Stretch = Stretch.Uniform;
        }

        private void saveBasicInformation()
        {
            contact.title = title.Text.Trim();
            contact.url = (url.Text.StartsWith("http://")) ? url.Text.Trim().ToLower() : "http://" + url.Text.Trim().ToLower();
            contact.company = company.Text.Trim();

            contact.homeAddress = new Address() { city = homeCity.Text, country = homeCountry.Text, state = homeState.Text, postalCode = homeZip.Text, street = homeStreet.Text, type = Engine.Type.HOME };
            contact.workAddress = new Address() { city = workCity.Text, country = workCountry.Text, state = workState.Text, postalCode = workZip.Text, street = workStreet.Text, type = Engine.Type.WORK };

            if ((firstName.Text.Trim() != "" && lastName.Text.Trim() != ""))
            {
                contact.name = new Name() { firstName = firstName.Text.Trim(), lastName = lastName.Text.Trim() };
                Communication.Visibility = Visibility.Visible;
                BasicInfo.Visibility = Visibility.Collapsed;
                Back.Visibility = Visibility.Visible;
            }
            else
                Name.Foreground = new SolidColorBrush(red);
        }

        private void saveCommunication()
        {
            contact.phones.Clear();
            contact.emails.Clear();
            foreach (ElementView ev in phones.Items)
                contact.phones.Add((Telephone)ev.item);
            foreach (ElementView ev in emails.Items)
                contact.emails.Add((Email)ev.item);

            Communication.Visibility = Visibility.Collapsed;
            Finish.Visibility = Visibility.Visible;
            Next.Content = "Finish";
        }

        private void image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "image"; // Default file name
            dlg.DefaultExt = ".jpg"; // Default file extension
            dlg.Filter = "Images (*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG|" + "All files (*.*)|*.*";

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                string[] splits = filename.Split(new char[] { '.' });
                string ext = splits[splits.Length - 1];
                string imagePath = root.profilePath + "\\images\\" + contact.name.formattedName + "." + ext;
                contact.photo.url = imagePath;
                contact.photo.ext = ext;
                setImageSource(image, imagePath);
            }
        }

        private void TextBox_MouseClick(object sender, MouseButtonEventArgs e)
        {
            TextBox t = (TextBox)sender;
            t.SelectAll();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox t = (TextBox)sender;
            t.Foreground = new SolidColorBrush(new Color() { ScA = 1, ScB = 0, ScG = 0, ScR = 0 });
        }

        private void Next_Click(object sender, RoutedEventArgs e)
        {
            if (BasicInfo.Visibility == Visibility.Visible)
                saveBasicInformation();
            else if (Communication.Visibility == Visibility.Visible)
                saveCommunication();
            else
            {
                System.IO.Directory.CreateDirectory(root.rootPath + contact.name.formattedName + "\\images\\groups\\");
                string addressBookPath = root.rootPath + contact.name.formattedName + "\\AddressBook.book";
                if (defaultConfiguration)
                    Utilities.save(contact, root.rootPath + "Configuration.config");
                Utilities.save(contact, root.rootPath + contact.name.formattedName + "\\Configuration.config"); 
                Utilities.save(root.addressBook, addressBookPath);
                root.Container.Children.Remove(popup);
                root.loadConfiguration();
                root.loadData();
            }
        }

        private void Back_Click(object sender, RoutedEventArgs e)
        {
            if (Communication.Visibility == Visibility.Visible)
            {
                Back.Visibility = Visibility.Collapsed;
                Communication.Visibility = Visibility.Collapsed;
                BasicInfo.Visibility = Visibility.Visible;
            }
            else
            {
                Communication.Visibility = Visibility.Visible;
                Finish.Visibility = Visibility.Collapsed;
                Next.Content = "Next";
            }
        }

        private void AddPhone_Click(object sender, RoutedEventArgs e)
        {
            Telephone t = new Telephone();
            contact.phones.Add(t);
            phones.Items.Add(new ElementView(contact, t, "Telephone"));
        }

        private void AddEmail_Click(object sender, RoutedEventArgs rea)
        {
            Email e = new Email();
            contact.emails.Add(e);
            emails.Items.Add(new ElementView(contact, e, "Email"));
        }

        private void Import_Click(object sender, RoutedEventArgs e)
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Contacts"; // Default file name
            dlg.DefaultExt = ".vcf"; // Default file extension
            dlg.Filter = "VCard (.vcf)|*.vcf"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                AddressBook import = urBook.Engine.VcfUtilities.VcfManager.import(filename);
                root.addressBook.contacts.AddRange(import.contacts);
                root.addressBook.groups.AddRange(import.groups);
            }
        }

        private void Tour_Click(object sender, RoutedEventArgs e)
        {
            //To-Do: Call Tour Window
        }
    }
}
